<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import MEcharts from '/@/components/MEcharts/MEcharts.vue';
  const props = defineProps({
    data: { type: Object as () => any, required: true },
  });

  const chartRef = ref();

  const option = ref<any>({
    tooltip: {
      trigger: 'item',
      show: true,
      backgroundColor: 'rgba(0,24,48,0.8)',
      borderColor: '#00f6ff',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      // appendToBody: true, // 关键设置
      formatter: function (params: any) {
        const data = params.data;
        if (data.realValue === null) {
          return `${data.name}<br/>实际：无数据<br/>标准：${data.standard ?? '-'}秒`;
        }
        const isOver = data.standard && data.realValue > data.standard;
        return `${data.name}<br/>实际：${data.realValue}秒<br/>标准：${data.standard ?? '-'}秒<br/>${
          isOver ? '<span style="color:#ff4d4f">超出标准</span>' : '<span style="color:#52c41a">正常</span>'
        }`;
      },
    },
    series: [
      {
        animationDelay() {
          return Math.random() * 400;
        },
        animationEasing: 'exponentialInOut',
        animationType: 'scale',
        center: ['50%', '50%'],
        color: ['#00ca59', '#00ca59', '#00ca59', '#00ca59'],
        data: props.data ?? [],
        name: '损失重量',
        radius: ['50%', '70%'],
        // roseType: 'radius',
        type: 'pie',
        labelLine: {
          show: false, // 关闭标签连接线（指示线）
        },
        label: {
          show: false, // 关闭标签文本
        },
      },
    ],
  });

  const myChart = ref<InstanceType<typeof MEcharts>>();
  const updateChart = () => {
    option.value.series[0].data = props.data[0] ?? [];
    myChart.value?.resizeHandler();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      updateChart();
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
  });

  watch(
    () => [props.data],
    () => updateChart(),
    { deep: true }
  );

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container">
    <m-echarts :option="option"></m-echarts>
  </div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
